/*
 * uart0-ss805x-priv.h
 *
 * The private definitions for uart0-ss805x.c.
 * Under normal conditions, it CAN be ignored by reader.
 *
 * Copyright (C) 2024 Sinh Micro, Inc.
 * Subject to the GNU Public License, version 2.
 *
 * Author: lixiang<lixiang@sinhmicro.com>
 * 
 * Encoding format: GB2312
 * Version: v1.2.2
 * Date: 2024-11-05
 */
#ifndef __UART0_SS805X_PRIV_H__
#define __UART0_SS805X_PRIV_H__

#include "hal-config.h"
#include "types.h"

#define UART0_BAUD_DIV (ROUND_DIV(SYS_SCLK_FREQ, CONFIG_UART0_BAUD_RATE))

/* caculate pre-divider and UART_BR value */
#if (UART0_BAUD_DIV > 13 * 512)
    #error("CONFIG_UART0_BAUD_RATE is invalid!")
#elif (UART0_BAUD_DIV > 5 * 512)
    #define UART0_BAUD_PRE_DIV      (13)
#else
    #if (REMAINDER(UART0_BAUD_DIV, 13) < REMAINDER(UART0_BAUD_DIV, 5))
        #define UART0_BAUD_PRE_DIV  (13)
    #else
        #define UART0_BAUD_PRE_DIV  (5)
    #endif
#endif

#define UART0_BAUD_BR_VAL           (UART0_BAUD_DIV / UART0_BAUD_PRE_DIV)

/* check the baud rate error */
#define UART0_REAL_BAUD (SYS_SCLK_FREQ / UART0_BAUD_PRE_DIV / UART0_BAUD_BR_VAL)
#if (UART0_REAL_BAUD > CONFIG_UART0_BAUD_RATE)
    #define UART0_BAUD_ERROR ((UART0_REAL_BAUD - CONFIG_UART0_BAUD_RATE) * \
                              100 / CONFIG_UART0_BAUD_RATE)
#else
    #define UART0_BAUD_ERROR ((CONFIG_UART0_BAUD_RATE - UART0_REAL_BAUD) * \
                              100 / CONFIG_UART0_BAUD_RATE)
#endif

#if (UART0_BAUD_ERROR > 3)
    #error("CONFIG_UART0_BAUD_RATE's error is too larger, please change it!")
#endif

/*
 * calculate the init SCON's value
 */
#if (UART0_BAUD_PRE_DIV == 13)
    #define UART0_BRPRE_VAL     (1 << 2)
#else
    #define UART0_BRPRE_VAL     (0)
#endif

#if (((512 - UART0_BAUD_BR_VAL) & 0x100) != 0)
    #define UART0_BR8_VAL       (1 << 5)
#else
    #define UART0_BR8_VAL       (0)
#endif

#if (CONFIG_UART0_PARITY == 1)
    #error("ODD parity is not supported!")
#elif (CONFIG_UART0_PARITY == 2)
    #define UART0_PARITY_VAL    (1 << 7)
#else
    #define UART0_PARITY_VAL    (0 << 7)
#endif


/* TI = 1 */
#define UART0_SCON_VAL          (0x02 | UART0_PARITY_VAL| UART0_BR8_VAL | \
                                 (CONFIG_UART0_USING_RX << 4) | UART0_BRPRE_VAL)

#endif
